const router = require('koa-router')()
const { getList, getDetail, newBlog, deleteBlog, updateBlog } = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')

router.prefix('/api/blog') // 路由前缀

// 请求所有的article
router.get('/all', async (ctx, next) => {
  const listsData = await getList()
  ctx.body = new SuccessModel(listsData)
})

// 获取单个文章详情
router.get('/detail', async (ctx, next) => {
  const { id } = ctx.query
  const listData = await getDetail(id)
  ctx.body = new SuccessModel(listData)
})

// 新增一篇博客
router.post('/newBlog', async (ctx, next) => {
  const { title, content, author } = ctx.request.body
  const newedData = await newBlog({ title, content, author })
  ctx.body = new SuccessModel(newedData)
})

// 修改博客
router.put('/update', async (ctx, next) => {
  const { id } = ctx.query
  const { title, content, author } = ctx.request.body
  const updatedData = await updateBlog(id, { title, content, author })
  ctx.body = new SuccessModel(updatedData)
})

// 删除一篇博客
router.delete('/delete', async (ctx, next) => {
  const { id, author } = ctx.query
  const deletedBlog = await deleteBlog(id, author)
  ctx.body = new SuccessModel(deletedBlog)
})

module.exports = router